package com.charging.business.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.charging.business.enums.ProvinceType;
import com.charging.business.exception.CustomizeException;
import com.charging.business.jin.*;
import com.charging.business.qin.QinOnLineRequest;
import com.charging.business.qin.QinOnLineResponse;
import com.charging.business.qin.TollDetail;
import com.charging.business.vo.CustomOnlineResponse;
import com.charging.business.vo.FeeExCalcRequest;
import com.charging.business.vo.FeeExCalcResponse;
import com.charging.business.vo.OnlineSpececResponse;
import com.charging.business.vo.obj.ProvinceFee;
import com.charging.business.vo.obj.SplitProvinceMini;
import com.charging.business.vo.obj.mini.MiniFeeResponse;
import com.charging.business.vo.obj.mini.ProvinceMini;
import com.charging.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author JerryLu
 * @date 2024/11/8 15:21
 * @description 名单请求工具类
 */
@Component
public class RosterUtils {

    private static final Logger logger = LoggerFactory.getLogger(RosterUtils.class);

    private static final BigDecimal ETC_DISCOUNT = new BigDecimal("0.95");
    private static final int MAX_AXLES = 18;
    private static final int BASE_AXLE_COUNT = 6;
    private static final BigDecimal COEFFICIENT_MULTIPLIER = new BigDecimal("0.2");

    private final RestTemplate restTemplate;

    @Value("${app.nameServerIp}")
    private String nameServerIp;

    @Value("${app.onLineServerIp}")
    private String onLineServerIp;

    @Autowired
    public RosterUtils(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public ArrayList<SplitProvinceMini> getMiniFee(String enStationId, String exStationId, int vehicleType, int exAxleCount, boolean bETC) throws CustomizeException {
        String fileName = String.format("PROVINCESTATION_MINFD_REQ_SENDER_%s.json", DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSSSSS));
        JSONObject json = new JSONObject();
        json.put("filename", fileName);
        json.put("encryptType", "");
        json.put("timestamp", "");
        json.put("version", "2.0");
        json.put("sign", "");
        json.put("signType", "None");
        JSONObject json1 = new JSONObject();
        json1.put("enID", enStationId);
        json1.put("exID", exStationId);
        json1.put("vType", vehicleType);
        json.put("bizContent", json1);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json; charset=utf-8");
        headers.set("Accept-Charset", "utf-8");
        HttpEntity<String> entity = new HttpEntity<>(json.toString(), headers);

        String errMsg = "";
        ArrayList<SplitProvinceMini> provs = new ArrayList<>();
        try {
            ResponseEntity<String> response = restTemplate.postForEntity(nameServerIp, entity, String.class);
            JSONObject jsonResult = JSON.parseObject(response.getBody());
            if (jsonResult.getInteger("statusCode") == 0) {
                String bizContent = jsonResult.getString("bizContent");
                MiniFeeResponse biz = JSON.parseObject(bizContent, MiniFeeResponse.class);
                if (biz.getCode() == 0) {
//                    String b = this.getFeeGt6("111|222|333", 7, true);
//                    System.out.println("@@@@@@");
//                    System.out.println(b);
//
//                    String c = this.getFeeGt6("90|111|0", 7, false);
//                    String c = this.getFeeGt6("0|90|111", 7, false);
//                    System.out.println("******");
//                    System.out.println(c);

                    for (ProvinceMini row : biz.getSplitProvince()) {
                        SplitProvinceMini mini = new SplitProvinceMini();
                        mini.provinceId = Integer.parseInt(row.getProv());
                        mini.calMinFeeFee = Math.toIntExact(row.getPFee());
                        mini.calMinFeeFee95 = Math.toIntExact(row.getPFee95());
                        mini.calMinFeeMileage = Math.toIntExact(row.getPM());
                        mini.tollIntervalsCount = row.getGroup().split("\\|").length;
                        mini.rateVersion = row.getMVer() + "|" + row.getMVer();
                        mini.tollIntervalsGroup = row.getGroup();
                        mini.feeGroup = row.getPFg();
                        if (vehicleType >= 10 && exAxleCount > 6 && Objects.equals(row.getProv(), ProvinceType.SHAN_XI.getCode())) {
                            //轴数大于6轴的货车
                            String gt6Str = this.getFeeGt6(row.getPFg(), exAxleCount, bETC);
                            mini.feeGroup = gt6Str;

                            List<Integer> gt6Units = Arrays.stream(gt6Str.split("\\|")).map(Integer::parseInt).collect(Collectors.toList());
                            int gt6TotalFee = gt6Units.stream().mapToInt(Integer::intValue).sum();
                            mini.calMinFeeFee = Math.toIntExact(gt6TotalFee);
//                    mini.calMinFeeFee95 = Math.toIntExact(gt6TotalFee * 0.95f);
                            mini.calMinFeeFee95 = new BigDecimal(gt6TotalFee).multiply(ETC_DISCOUNT).setScale(0, RoundingMode.HALF_DOWN).intValue();
                        }
                        /**
                         * todo：1、山西的最小费的应收：不管是CPC还是ETC还是大于小于6轴等特殊计算的情况。都应该是各收费单元的总和。总和上处已算过
                         *       2、陕西即用费额里得真实实收即可
                         */
                        //计算应收
                        mini.ziMinPayFee = Math.toIntExact(mini.calMinFeeFee);
                        //计算实收。方便后续步骤获取判断阙值
                        mini.ziMinFee = Math.toIntExact(row.getPFee());
                        provs.add(mini);
                    }
                } else {
                    errMsg = String.format("最小费额计费失败:[%s]", biz.getCodeInfo());
                    throw new CustomizeException(errMsg);
                }
            } else {
                errMsg = String.format("最小费额计费失败:[%s]", jsonResult.getString("errorMsg"));
                throw new CustomizeException(errMsg);
            }

        } catch (ResourceAccessException e) {
            throw new CustomizeException("最小费额计费超时");
        } catch (CustomizeException e) {
            throw new CustomizeException(e.getCustomMessage());
        }
        return provs;
    }

    public String getFeeGt6(String tollUnits, int exAxleCount, boolean isEtc) {
        if (exAxleCount > 18) {
            exAxleCount = 18;
        }

        List<Integer> units = Arrays.stream(tollUnits.split("\\|")).map(Integer::parseInt).collect(Collectors.toList());

        // 计算轴数系数
        BigDecimal axleCoefficient = calculateAxleCoefficient(exAxleCount);

        // 1、计算每个收费单元的金额，四舍五入精确到分
        int finalExAxleCount = exAxleCount;
        List<Integer> calculatedUnits = units.stream().map(unit -> calculateUnitFee(unit, finalExAxleCount)).collect(Collectors.toList());

        /**
         * 2、计算本省货六最小费额实收金额
         */
        int totalFee = calculatedUnits.stream().mapToInt(Integer::intValue).sum();
        //CPC收费,四舍五入取整到元
        int cpcTotalFee = PayUtil.mtcFinalFee(totalFee);
//        if (!isEtc) {
//            int lastUnit = cpcTotalFee - totalFee;
//            if (lastUnit < 0) {
//                int maxUnit = calculatedUnits.stream().max(Integer::compare).orElse(0);
//                System.out.println("其他单元最大：" + maxUnit);
//                int lastUnitMount = maxUnit + (cpcTotalFee - totalFee);
//                lastUnit = 0;
//                for (int i = 0; i < calculatedUnits.size(); i++) {
//                    if (calculatedUnits.get(i) == maxUnit) {
//                        calculatedUnits.set(i, lastUnitMount);
//                        break;
//                    }
//                }
//                System.out.println("有0新units：" + calculatedUnits);
//            }
//        }
        // 计算最后一个收费单元的金额
        int lastUnitAmount = calculateLastUnitAmount(calculatedUnits, cpcTotalFee);
        // 替换最后一个收费单元的金额
        List<Integer> finalUnits = replaceLastUnit(calculatedUnits, lastUnitAmount);
        if (isEtc) {
            //计算ETC应收
            int etcFee = totalFee;
            //计算ETC实收,需进行四舍五不入精确到分
            int etcCalFee = PayUtil.round40(totalFee);
            //计算ETC95折实收,四舍五入精确到分
            int etcCal95Fee = (new BigDecimal(etcCalFee).multiply(ETC_DISCOUNT).setScale(0, RoundingMode.HALF_DOWN).intValue());
//        int etcCal95Fee = Math.round(etcCalFee * 0.95f);
            int cpcCal95Fee = (new BigDecimal(cpcTotalFee).multiply(ETC_DISCOUNT).setScale(0, RoundingMode.HALF_DOWN).intValue());
//        int cpcCal95Fee = Math.round(cpcTotalFee * 0.95f);


            if (etcCal95Fee < cpcCal95Fee) {
                lastUnitAmount = calculateLastUnitAmount(calculatedUnits, etcCal95Fee);
                finalUnits = replaceLastUnit(calculatedUnits, lastUnitAmount);
            } else {
                lastUnitAmount = calculateLastUnitAmount(calculatedUnits, cpcCal95Fee);
                finalUnits = replaceLastUnit(calculatedUnits, lastUnitAmount);
            }
        }

        // 计算最后一个收费单元的金额
//        int lastUnitAmount = calculateLastUnitAmount(calculatedUnits, cpcTotalFee);
//        System.out.println("lastUnitAmount: " + lastUnitAmount);
//
//        // 替换最后一个收费单元的金额
//        List<Integer> finalUnits = replaceLastUnit(calculatedUnits, lastUnitAmount);
//        System.out.println("finalUnits: " + finalUnits);

        // 根据是否是ETC计算最终费用
//        int finalTotalFee = calculateFinalTotalFee(finalUnits, isEtc);

        // 返回格式化后的字符串
        return formatResult(finalUnits);
    }

    private int calculateUnitFee(int unit, int exAxleCount) {
        return Math.round(unit * (1 + (exAxleCount - 6) * 0.2f));
    }

    private BigDecimal calculateAxleCoefficient(int exitAxles) {
        if (exitAxles > MAX_AXLES) {
            exitAxles = MAX_AXLES;
        }
        return BigDecimal.ONE.add(new BigDecimal(exitAxles - BASE_AXLE_COUNT).multiply(COEFFICIENT_MULTIPLIER));
    }

    private int calculateLastUnitAmount(List<Integer> units, int roundedTotalFee) {
        int otherUnitsTotal = units.subList(0, units.size() - 1).stream().mapToInt(Integer::intValue).sum();
        int lastUnit = roundedTotalFee - otherUnitsTotal;

        if (lastUnit < 0) {
            // 如果最后一个单元为负数，调整最大值
            int maxUnit = units.stream().max(Integer::compare).orElse(0);
//            lastUnit = 0;
            for (int i = 0; i < units.size(); i++) {
                if (units.get(i) == maxUnit) {
                    units.set(i, maxUnit + lastUnit);
                    break;
                }
            }

        }
        return Math.max(lastUnit, 0);
    }

    private List<Integer> replaceLastUnit(List<Integer> units, int lastUnitAmount) {
        List<Integer> result = new ArrayList<>(units);
        result.set(result.size() - 1, lastUnitAmount);
        return result;
    }

//    private int calculateFinalTotalFee(List<Integer> units, boolean isEtc) {
//        int totalFee = units.stream().mapToInt(Integer::intValue).sum();
//        System.out.println("aa: " + totalFee);
//        if (isEtc) {
//            BigDecimal etcTotalFee = BigDecimal.valueOf(new BigDecimal(totalFee).multiply(ETC_DISCOUNT).setScale(0, RoundingMode.HALF_DOWN).intValue());
//            BigDecimal cpcTotalFee = BigDecimal.valueOf(new BigDecimal(totalFee).setScale(0, RoundingMode.HALF_UP).multiply(ETC_DISCOUNT).setScale(0, RoundingMode.HALF_DOWN).intValue());
//            return etcTotalFee.min(cpcTotalFee).intValue();
//        } else {
//            return totalFee;
//        }
//    }

    private String formatResult(List<Integer> units) {
        return String.join("|", units.stream().map(String::valueOf).toArray(String[]::new));
    }

    /**
     * 山西获取在线计费
     *
     * @param request
     * @return
     * @throws CustomizeException
     */
    public CustomOnlineResponse getJinExOnlineFee(JinOnLineRequest request, FeeExCalcResponse resp) throws CustomizeException {
        CustomOnlineResponse infos = new CustomOnlineResponse();
        String msg = "";
        JSONObject json = JSONObject.parseObject(JSON.toJSONString(request));
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json; charset=utf-8");
        headers.set("Accept-Charset", "utf-8");
        headers.set("Accept", "application/json");
        HttpEntity<String> entity = new HttpEntity<>(json.toString(), headers);

//        RestTemplate restTemplate = new RestTemplate();
        String respTime = DateUtils.getTimeT();
        try {
            ResponseEntity<String> response = restTemplate.postForEntity(onLineServerIp, entity, String.class);
            JSONObject jsonResult = JSON.parseObject(response.getBody());
            if (Objects.equals(jsonResult.getString("code"), "20000") || Objects.equals(jsonResult.getString("code"), "30000")) {
                if (Objects.equals(jsonResult.getString("code"), "20000")) {
                    resp.setProRequestTime(respTime);
                    resp.setProResponseTime(DateUtils.getTimeT());
                    resp.setExitFeeType(4);
                }
                if (Objects.equals(jsonResult.getString("code"), "30000")) {
                    resp.setMinRequestTime(respTime);
                    resp.setMinResponseTime(DateUtils.getTimeT());
                    resp.setExitFeeType(5);
                }
                String data = jsonResult.getString("data");
                JinOnlineResponse res = JSON.parseObject(data, JinOnlineResponse.class);
                OnlineSpececResponse info = JSON.parseObject(JSON.toJSONString(res), OnlineSpececResponse.class);
                if (info.getCalculateResult() == 1) {
                    ArrayList<ProvinceFee> provs = new ArrayList<>();
                    for (ProvinceFees row : res.getProvinceFees()) {
                        ProvinceFee pr = JSON.parseObject(JSON.toJSONString(row), ProvinceFee.class);
                        pr.setFeeGroup(row.getChargefeeGroup());
                        pr.setDiscountFeeGroup(row.getChargeDiscountGroup());
                        provs.add(pr);
                    }
                    info.setProvinceFees(provs);
//        ProvinceFee provs = JSON.parseObject(JSON.toJSONString(provinceFees), ProvinceFee.class);
//        info.setProvinceFees(provs);
//        } else {
//            logger.error("在线计费失败：{}", jsonResult.getString("message"));
//            throw new CustomizeException(jsonResult.getString("message"));
//        }
                    info.check(request.getMediaType());
                    infos.setOnlineSpececResponse(info);
                    infos.setEnStationId(res.getEnStationId());
                } else {
                    if (info.getCalculateResult() == 2) {
                        msg = "入口站有误-路径不可达";
                    } else if (info.getCalculateResult() == 3) {
                        msg = "路径信息不可拟合";
                    } else if (info.getCalculateResult() == 4) {
                        msg = "拟合超时";
                    } else if (info.getCalculateResult() == 5) {
                        msg = "非跨省通行";
                    }
                    msg = "在线特情计费失败: " + msg;
                    logger.error(String.format("在线特情计费失败%s", msg));
                    infos.setOnlineSpececResponse(info);
                }
            } else {
                logger.error(String.format("在线特情%s", jsonResult.getString("message")));
                OnlineSpececResponse info = new OnlineSpececResponse();
                info.setCalculateResult(99);
                infos.setOnlineSpececResponse(info);
            }
        } catch (ResourceAccessException e) {
            OnlineSpececResponse info = new OnlineSpececResponse();
            info.setCalculateResult(0);
            infos.setOnlineSpececResponse(info);
            logger.error("在线特情计费超时");
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return infos;
    }

    /**
     * 陕西获取在线计费
     *
     * @param request
     * @return
     * @throws CustomizeException
     */
    public CustomOnlineResponse getQinExOnlineFee(QinOnLineRequest request, FeeExCalcResponse response) throws CustomizeException {
        CustomOnlineResponse infos = new CustomOnlineResponse();
//        String fileName = String.format("PROVINCESTATION_SPECEC_REQ_%s_%s.json", request.getExTollLaneId(), DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSSSSS));
//
//        JSONObject json = JSONObject.parseObject(JSON.toJSONString(request));
//        HttpHeaders headers = new HttpHeaders();
//        headers.set("Content-Type", "application/json; charset=utf-8");
//        headers.set("Accept-Charset", "utf-8");
//        HttpEntity<String> entity = new HttpEntity<>(json.toString(), headers);
//
//        RestTemplate restTemplate = new RestTemplate();
//        ResponseEntity<String> response = restTemplate.postForEntity("BASE_URL" + "/receive/gantry/unpaid", entity, String.class);
//        JSONObject jsonResult = JSON.parseObject(response.getBody());
//        if (jsonResult.getInteger("code") > 0) {
//
//        } else {
//            info = JSON.parseObject(response.getBody(), OnlineSpececReponse.class);
//        }

        String data = "{\"responseId\":\"cdb52964-afdb-4549-bdd1-422a2ad4358b\",\"tollSupport\":2,\"fittingSign\":0,\"calculateResult\":1,\"mediaType\":\"1\",\"mediaNo\":\"61021940230030682612\",\"enStationId\":\"G3001610010040\",\"enTollLaneId\":\"G30016100100401010130\",\"enTime\":\"2024-11-13T07:38:56\",\"resultVoucher\":\"\",\"payFee\":2610,\"fee\":2480,\"discountFee\":140,\"splitAmount\":2470,\"feeMileage\":55257,\"isDiscount\":1,\"spare1\":0,\"tollDetail\":[{\"responseId\":\"cdb52964-afdb-4549-bdd1-422a2ad4358b\",\"serialNum\":0,\"provinceId\":\"61\",\"payFee\":2610,\"fee\":2480,\"discountFee\":140,\"splitAmount\":2470,\"feeMileage\":55257,\"tollIntervalsCount\":14,\"oriintervalsGroup\":\"G300161001002510|G300161001000820|G300161001000720|G300161001000620|G300161001000520|G300161001000420|G300161001000220|G300161001000120|G300161001003520|G300161001001920|S000161001000210|S000161001000310|S000161001000410|S000161001000510\",\"tollIntervalsGroup\":\"G300161001002510|G300161001000820|G300161001000720|G300161001000620|G300161001000520|G300161001000420|G300161001000220|G300161001000120|G300161001003520|G300161001001920|S000161001000210|S000161001000310|S000161001000410|S000161001000510\",\"transTimeGroup\":\"2024-11-13T07:38:56|2024-11-13T07:44:47|2024-11-13T07:47:09|2024-11-13T07:48:37|2024-11-13T07:49:58|2024-11-13T07:53:07|2024-11-13T07:55:13|2024-11-13T07:57:11|2024-11-13T07:59:36|2024-11-13T08:04:42|2024-11-13T08:07:47|2024-11-13T08:08:36|2024-11-13T08:11:02|2024-11-13T08:13:28\",\"nodeSource\":\"1|1|1|1|1|1|1|1|1|1|1|1|1|1\",\"chargefeeGroup\":\"0|356|115|93|76|181|169|94|149|105|171|132|228|611\",\"chargeDiscountGroup\":\"0|19|6|5|4|9|9|5|8|5|9|7|12|32\",\"spare1\":0,\"spare3\":null,\"spare4\":null}]}";
        QinOnLineResponse res = JSON.parseObject(data, QinOnLineResponse.class);
        OnlineSpececResponse info = JSON.parseObject(JSON.toJSONString(res), OnlineSpececResponse.class);
        ArrayList<ProvinceFee> provs = new ArrayList<>();
        for (TollDetail row : res.getTollDetail()) {
            ProvinceFee pr = JSON.parseObject(JSON.toJSONString(row), ProvinceFee.class);
            pr.setFeeGroup(row.getChargefeeGroup());
            pr.setDiscountFeeGroup(row.getChargeDiscountGroup());
            provs.add(pr);
        }
        info.setProvinceFees(provs);
        info.check(request.getMediaType());
        if (res.getTollSupport() == 2) {
            response.setExitFeeType(5);
        } else {
            response.setExitFeeType(4);
        }
        infos.setOnlineSpececResponse(info);
        infos.setEnStationId(res.getEnStationId());
        return infos;
    }

    /**
     * 山西无通行介质获取入口信息
     *
     * @param onLineRes
     * @param request1
     * @return
     * @throws CustomizeException
     */
    public List<EnStations> getJinExOnlineFeeForNoCard(JinOnLineRequest onLineRes, FeeExCalcRequest request) throws CustomizeException {
        List<EnStations> stations = new ArrayList<>();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json; charset=utf-8");
        headers.set("Accept-Charset", "utf-8");
        headers.set("Accept", "application/json");
        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(onLineRes), headers);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(onLineServerIp, entity, String.class);
            EnStationsResponse apiResponse = JSON.parseObject(response.getBody(), EnStationsResponse.class);
            if (Objects.equals(apiResponse.getCode(), "10001")) {
                stations = apiResponse.getData().getEnStationsResp().getEnStations();
            } else {
                String ms = apiResponse.getMessage();
                if (ms.contains("{\"enStations\":[]}") || apiResponse.getData().getEnStationsResp().getEnStations().isEmpty()) {
                    ms = "无通行介质在线特情计费失败：无入口信息返回";
                } else {
                    ms = String.format("在线特情%s", ms);
                }

                if (request.getEnStationId().isEmpty() || request.getEnStationHex().isEmpty()) {
                    logger.error(ms);
                    throw new CustomizeException(ms);
                } else {
                    logger.error(ms + ",走兜底");
                }
            }
        } catch (ResourceAccessException e) {
            throw new CustomizeException("在线查询入口信息超时");
        }
        return stations;
    }

    /**
     * 陕西无卡特情获取在线计费
     *
     * @param request
     * @return
     * @throws CustomizeException
     */
    public CustomOnlineResponse getQinExOnlineFeeForNoCard(QinOnLineRequest request, FeeExCalcResponse response) throws CustomizeException {
        CustomOnlineResponse infos = new CustomOnlineResponse();
//        String fileName = String.format("PROVINCESTATION_SPECEC_REQ_%s_%s.json", request.getExTollLaneId(), DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSSSSS));
//
//        JSONObject json = JSONObject.parseObject(JSON.toJSONString(request));
//        HttpHeaders headers = new HttpHeaders();
//        headers.set("Content-Type", "application/json; charset=utf-8");
//        headers.set("Accept-Charset", "utf-8");
//        HttpEntity<String> entity = new HttpEntity<>(json.toString(), headers);
//
//        RestTemplate restTemplate = new RestTemplate();
//        ResponseEntity<String> response = restTemplate.postForEntity("BASE_URL" + "/receive/gantry/unpaid", entity, String.class);
//        JSONObject jsonResult = JSON.parseObject(response.getBody());
//        if (jsonResult.getInteger("code") > 0) {
//
//        } else {
//            info = JSON.parseObject(response.getBody(), OnlineSpececReponse.class);
//        }

        String data = "{\"responseId\":\"cdb52964-afdb-4549-bdd1-422a2ad4358b\",\"tollSupport\":2,\"fittingSign\":0,\"calculateResult\":1,\"mediaType\":\"1\",\"mediaNo\":\"61021940230030682612\",\"enStationId\":\"G3001610010040\",\"enTollLaneId\":\"G30016100100401010130\",\"enTime\":\"2024-11-13T07:38:56\",\"resultVoucher\":\"\",\"payFee\":2610,\"fee\":2480,\"discountFee\":140,\"splitAmount\":2470,\"feeMileage\":55257,\"isDiscount\":1,\"spare1\":0,\"tollDetail\":[{\"responseId\":\"cdb52964-afdb-4549-bdd1-422a2ad4358b\",\"serialNum\":0,\"provinceId\":\"61\",\"payFee\":2610,\"fee\":2480,\"discountFee\":140,\"splitAmount\":2470,\"feeMileage\":55257,\"tollIntervalsCount\":14,\"oriintervalsGroup\":\"G300161001002510|G300161001000820|G300161001000720|G300161001000620|G300161001000520|G300161001000420|G300161001000220|G300161001000120|G300161001003520|G300161001001920|S000161001000210|S000161001000310|S000161001000410|S000161001000510\",\"tollIntervalsGroup\":\"G300161001002510|G300161001000820|G300161001000720|G300161001000620|G300161001000520|G300161001000420|G300161001000220|G300161001000120|G300161001003520|G300161001001920|S000161001000210|S000161001000310|S000161001000410|S000161001000510\",\"transTimeGroup\":\"2024-11-13T07:38:56|2024-11-13T07:44:47|2024-11-13T07:47:09|2024-11-13T07:48:37|2024-11-13T07:49:58|2024-11-13T07:53:07|2024-11-13T07:55:13|2024-11-13T07:57:11|2024-11-13T07:59:36|2024-11-13T08:04:42|2024-11-13T08:07:47|2024-11-13T08:08:36|2024-11-13T08:11:02|2024-11-13T08:13:28\",\"nodeSource\":\"1|1|1|1|1|1|1|1|1|1|1|1|1|1\",\"chargefeeGroup\":\"0|356|115|93|76|181|169|94|149|105|171|132|228|611\",\"chargeDiscountGroup\":\"0|19|6|5|4|9|9|5|8|5|9|7|12|32\",\"spare1\":0,\"spare3\":null,\"spare4\":null}]}";
        QinOnLineResponse res = JSON.parseObject(data, QinOnLineResponse.class);
        OnlineSpececResponse info = JSON.parseObject(JSON.toJSONString(res), OnlineSpececResponse.class);
        ArrayList<ProvinceFee> provs = new ArrayList<>();
        for (TollDetail row : res.getTollDetail()) {
            ProvinceFee pr = JSON.parseObject(JSON.toJSONString(row), ProvinceFee.class);
            pr.setFeeGroup(row.getChargefeeGroup());
            pr.setDiscountFeeGroup(row.getChargeDiscountGroup());
            provs.add(pr);
        }
        info.setProvinceFees(provs);
        info.check(request.getMediaType());
        if (res.getTollSupport() == 2) {
            response.setExitFeeType(5);
        } else {
            response.setExitFeeType(4);
        }
        infos.setOnlineSpececResponse(info);
        infos.setEnStationId(res.getEnStationId());
        return infos;
    }

}
